package com.sbp.message.consumer;

import com.dap.api.ISunriseService;
import com.dap.param.StringInput;
import com.sbp.message.api.entity.*;
import com.sbp.message.entity.ConsumerMessageRecord;
import com.sbp.message.service.ConsumerMessageRecordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

public class ServiceProcessor {
    private static final Logger logger = LoggerFactory.getLogger(ServiceProcessor.class);

    private ConsumerMessageRecordService consumerMessageRecordService;
    public void setConsumerMessageRecordService(ConsumerMessageRecordService consumerMessageRecordService) {
        this.consumerMessageRecordService = consumerMessageRecordService;
    }




    // 插入本地消费记录
    public ConsumerMessageRecord insertConsumerMessageRecord(Message message, String group, LocalRecordStatus status) {
        ConsumerMessageRecord record = new ConsumerMessageRecord();
        record.setMessageId(message.getId());
        record.setAppId(group);
        record.setDestination(message.getDestination());
        record.setType(LocalRecordType.consumer.getValue());
        record.setStatus(status.getValue());
        record.setCreateTime(new Date());
        consumerMessageRecordService.insert(record);

        return record;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean executeServiceAndInsertRecord(Message message, String group, ISunriseService service, StringInput stringInput) {
        try {
            insertConsumerMessageRecord(message, group, LocalRecordStatus.processing);
            logger.info("local record inserted, messageId={}", message.getId());
        } catch (Exception e) {
            logger.info("", e);
            return false;
        }

        service.execute(null, stringInput);

        int updateRowCount = consumerMessageRecordService.updateStatus(message.getId(), group, LocalRecordStatus.succeed);
        logger.info("local record updated, messageId={}, updateRowCount={}", message.getId(), updateRowCount);

        return true;
    }
}